/*
 * @Autor: dingxiaolin
 * @Date: 2021-06-02 13:12:43
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2021-07-22 11:59:15
 */
import { ActionContext } from 'vuex'
import { IUserState } from './state'
import { getUserInfo, login } from '@/api/system/user'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { storage } from '@/utils/Storage'
import store from '@/store'
import { IStore } from '@/store/types'
import { ACTIVE_APP, APPS, PERMISSIONS, ADMINTYPE } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import router from '@/router'


export const actions = {
    // 登录
    async login({ commit }: ActionContext<IUserState, IStore>, userInfo) {
        try {
            const data = await login(userInfo)
            storage.set(ACCESS_TOKEN, data.accessToken.token, data.accessToken.expire)
            commit('setToken', data.accessToken.token)
            commit('setAuthInfo', data.authUser)
            store.dispatch('user/getApps')
            return Promise.resolve(data)
        } catch (e) {
            return Promise.reject(e)
        }
    },

    // 获取用户信息
    getApps() {
        getUserInfo().then((res) => {
            store.commit('user/setUserInfo', res)
            if (res.apps.length > 0) {
                storage.set(PERMISSIONS, res.permissions)
                storage.set(APPS, res.apps)
                storage.set(ADMINTYPE, res.adminType)
                if (location.search.includes('&')) {
                    const redirect = location.search.split('&')[0].split('=')[1];
                    const app = location.search.split('&')[1].split('=')[1];
                    storage.set(ACTIVE_APP, app)
                    store.dispatch('asyncRoute/generateRoutes').then(() => {
                        router.push(redirect)
                    })
                    return
                };
                res.apps.map(v => {
                    if (v.active) {
                        storage.set(ACTIVE_APP, v.code)
                        router.push({ path: '/' })
                    }
                })
            } else {
                Modal.error({
                    title: '提示：',
                    content: '无菜单权限，请联系管理员',
                    okText: '确定',
                    onOk: () => {
                        storage.clear();
                        window.location.reload();
                    }
                })
            }
        })
    },

    // 登出
    async logout({ commit }: ActionContext<IUserState, IStore>) {
        return new Promise((resolve) => {
            storage.clear()
            resolve('')
        })
    }
}
